/**
 * 
 */
package org.tea.springdata.web.utils;

import java.security.MessageDigest;

/**
 * @author John zhang
 * @version 0.1
 */
public class CAUtils {

	private static final String MD5_ALGORITHM = "MD5";
	private static final String SHA1_ALGORITHM = "SHA1";

	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static byte[] encodeSHA1( byte[] data ) {
		if ( data == null ) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance ( SHA1_ALGORITHM );
			messageDigest.update ( data );
			return messageDigest.digest ();
		} catch ( Exception e ) {
			throw new RuntimeException ( e );
		}

	}
	
	public static byte[] encodeMD5( byte[] data ) {
		if ( data == null ) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance ( MD5_ALGORITHM );
			messageDigest.update ( data );
			return messageDigest.digest ();
		} catch ( Exception e ) {
			throw new RuntimeException ( e );
		}

	}

	public static String toHexString( byte[] data ) {
		int len = data.length;
		StringBuilder buf = new StringBuilder ( len * 2 );
		for ( int j = 0; j < len; j++ ) {
			buf.append ( HEX_DIGITS[( data[j] >> 4 ) & 0x0f] );
			buf.append ( HEX_DIGITS[data[j] & 0x0f] );
		}
		return buf.toString ();
	}
}
